package com.huluobo.a2110mvvmjetpackdemo2.livedata;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import android.os.Bundle;
import android.widget.TextView;

import com.huluobo.a2110mvvmjetpackdemo2.R;

public class StudentActivity extends AppCompatActivity {

    private TextView tvMessage;
    private StudentViewModel studentViewModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_student);

        tvMessage = findViewById(R.id.tvMessage);
        studentViewModel = new ViewModelProvider(this).get(StudentViewModel.class);

        //new出一个学生对象,给学生对象赋值
        Student student = new Student("LC", 1, 90);
        //往viewModel中的livedata赋值
        studentViewModel.setStudentMutableLiveData(student);

        //观察viewModel中Livedata值的变化,来给textView赋值
        studentViewModel.getStudentMutableLiveData().observe(this, new Observer<Student>() {
            @Override
            public void onChanged(Student student) {
                tvMessage.setText("分数:" + student.getScore());
            }
        });
    }
}